#include "aipredictionwidget.h"
#include "ui_aipredictionwidget.h"

AIPredictionWidget::AIPredictionWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AIPredictionWidget)
{
    ui->setupUi(this);
    manger = new QNetworkAccessManager(this);
    ui->customCropGroupBox->setVisible(false);
    Ui_PushButton();
    // 初始化农作物数据库
    cropRequirements = {
        {"番茄", {"番茄", 18.0, 25.0, 60, 80, 25000, 40000, 10, 12, 14}},
        {"黄瓜", {"黄瓜", 20.0, 28.0, 70, 90, 20000, 35000, 12, 14, 12}},
        {"生菜", {"生菜", 15.0, 22.0, 60, 70, 15000, 25000, 8, 10, 10}},
        {"草莓", {"草莓", 15.0, 25.0, 60, 70, 20000, 30000, 10, 12, 12}},
        {"土豆", {"土豆", 15.0, 25.0, 60, 70, 20000, 30000, 10, 12, 12}},
        {"南瓜", {"南瓜", 15.0, 25.0, 60, 70, 20000, 30000, 10, 12, 12}},
        {"胡萝卜", {"胡萝卜", 15.0, 25.0, 60, 70, 20000, 30000, 10, 12, 12}}
    };

    // 填充农作物选择框
    for(auto it = cropRequirements.begin(); it != cropRequirements.end(); ++it) {
        ui->cropComboBox->addItem(it.key());
    }

    // 连接信号
    connect(ui->cropComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &AIPredictionWidget::on_cropComboBox_currentIndexChanged);

    connect(ui->getAdviceButton, &QPushButton::clicked,
            this, &AIPredictionWidget::on_getAdviceButton_clicked);

    connect(manger, &QNetworkAccessManager::finished, this, &AIPredictionWidget::http_recv); //AI接收
}

AIPredictionWidget::~AIPredictionWidget()
{
    delete ui;
}

void AIPredictionWidget::Ui_PushButton()
{
    ui->addCropButton->setStyleSheet(
        // 基础样式
        "QPushButton {"
        "   background-color: #4CAF50;"  // 绿色背景
        "   color: white;"               // 白色文字
        "   border: 2px solid #45a049;"  // 深绿色边框
        "   border-radius: 8px;"         // 圆角效果
        "   padding: 8px 16px;"          // 内边距
        "   font-weight: bold;"          // 加粗字体
        "   font-size: 12px;"            // 字体大小
        "}"

        // 鼠标悬停效果
        "QPushButton:hover {"
        "   background-color: #45a049;"  // 深绿色背景
        "   border: 2px solid #3d8b40;"   // 更深的边框
        "}"

        // 按下特效
        "QPushButton:pressed {"
        "   background-color: #3d8b40;"  // 深绿色
        "   border: 2px solid #367133;"  // 深边框
        "   padding-top: 9px;"           // ↓ 模拟按下凹陷效果
        "   padding-bottom: 7px;"         // ↑
        "}"
    );
}

void AIPredictionWidget::http_recv(QNetworkReply *reply)
{
    ui->getAdviceButton->setEnabled(true); // 重新启用按钮

    // 读取响应数据并保存
    QByteArray responseData = reply->readAll();

    if (reply->error() != QNetworkReply::NoError) {
        ui->aiResponseTextEdit->appendPlainText("⚠️ 网络错误: " + reply->errorString());
        ui->aiResponseTextEdit->appendPlainText("响应内容: " + responseData); // 显示响应内容
        reply->deleteLater();
        return;
    }

    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(responseData, &jsonError);
    if (jsonError.error != QJsonParseError::NoError) {
        ui->aiResponseTextEdit->appendPlainText("❌ JSON解析错误: " + jsonError.errorString());
        ui->aiResponseTextEdit->appendPlainText("响应内容: " + responseData);
        reply->deleteLater();
        return;
    }

    QJsonObject root = doc.object();

    // 检查是否有错误信息
    if (root.contains("error")) {
        QJsonObject errorObj = root["error"].toObject();
        QString errorMsg = errorObj["message"].toString();
        ui->aiResponseTextEdit->appendPlainText("❌ API错误: " + errorMsg);
        return;
    }

    // 解析响应内容
    if (root.contains("choices")) {
        QJsonArray choices = root["choices"].toArray();
        if (!choices.isEmpty()) {
            QJsonObject choice = choices[0].toObject();
            QJsonObject message = choice["message"].toObject();
            QString content = message["content"].toString().trimmed();

            // 移除Markdown标记（可选）
            content.replace("**", "").replace("###", "\n➤ ");

            ui->aiResponseTextEdit->setPlainText(content);
            qDebug() << content;
            reply->deleteLater();
            return;
        }
    }

    // 错误处理
    ui->aiResponseTextEdit->appendPlainText("❌ 解析响应失败\n原始响应:\n" + doc.toJson());
    reply->deleteLater();
}

// AIPredictionWidget.cpp 添加
void AIPredictionWidget::on_addCropButton_clicked()
{
    // 显示自定义作物输入区域
    ui->customCropGroupBox->setVisible(true);
    ui->cropComboBox->setEnabled(false);
    ui->getAdviceButton->setEnabled(false);
}

void AIPredictionWidget::on_saveCustomCropButton_clicked()
{
    QString name = ui->cropNameEdit->text().trimmed();
    if(name.isEmpty()) {
        QMessageBox::warning(this, "错误", "作物名称不能为空");
        return;
    }

    if(cropRequirements.contains(name)) {
        QMessageBox::warning(this, "错误", "该作物已存在");
        return;
    }

    // 创建新作物需求结构
    CropRequirement newCrop = {
        name,
        static_cast<float>(ui->minTempSpin->value()),
        static_cast<float>(ui->maxTempSpin->value()),
        static_cast<int>(ui->minHumiditySpin->value()),
        static_cast<int>(ui->maxHumiditySpin->value()),
        static_cast<int>(ui->minLightSpin->value()),
        static_cast<int>(ui->maxLightSpin->value()),
        static_cast<int>(ui->idealTempTimeSpin->value()),
        static_cast<int>(ui->idealHumidityTimeSpin->value()),
        static_cast<int>(ui->idealLightTimeSpin->value())
    };

    // 添加到映射
    cropRequirements.insert(name, newCrop);

    // 更新下拉框
    ui->cropComboBox->addItem(name);
    ui->cropComboBox->setCurrentText(name);

    // 重置界面
    ui->customCropGroupBox->setVisible(false);
    ui->cropComboBox->setEnabled(true);
    ui->getAdviceButton->setEnabled(true);

    QMessageBox::information(this, "成功", "自定义作物添加成功");
}

void AIPredictionWidget::setEnvironmentData(int tempTime, int humidityTime, int lightTime)
{
    currentTempTime = tempTime / 3600; // 转换为小时
    currentHumidityTime = humidityTime / 3600;
    currentLightTime = lightTime / 3600;

    ui->lcdNumber->display(tempTime);
    ui->lcdNumber_2->display(humidityTime);
    ui->lcdNumber_3->display(lightTime);

    ui->tempHoursLabel->setText(QString::number(currentTempTime) + " 小时");
    ui->humidityHoursLabel->setText(QString::number(currentHumidityTime) + " 小时");
    ui->lightHoursLabel->setText(QString::number(currentLightTime) + " 小时");
}

void AIPredictionWidget::on_cropComboBox_currentIndexChanged(int index)
{
    QString cropName = ui->cropComboBox->currentText();
    if(cropRequirements.contains(cropName)) {
        CropRequirement req = cropRequirements[cropName];

        ui->cropInfoLabel->setText(
            QString("温度范围: %1°C-%2°C\n湿度范围: %3%-%4%\n光照强度: %5-%6 lux")
            .arg(req.minTemp).arg(req.maxTemp)
            .arg(req.minHumidity).arg(req.maxHumidity)
            .arg(req.minLight).arg(req.maxLight)
        );
    }
}

void AIPredictionWidget::on_getAdviceButton_clicked()
{

    // 获取当前选择的农作物信息
    QString cropName = ui->cropComboBox->currentText();
    if (!cropRequirements.contains(cropName)) {
        ui->aiResponseTextEdit->setPlainText("未找到该农作物的种植要求");
        return;
    }
    CropRequirement req = cropRequirements[cropName];

    // 动态生成提示词（关键改进）
    QString prompt = QString("请基于以下条件给出种植建议：\n"
                            "作物品种：%1\n"
                            "理想温度：%2-%3°C（当前达标：%4小时）\n"
                            "理想湿度：%5-%6%%（当前达标：%7小时）\n"
                            "理想光照：%8-%9 lux（当前达标：%10小时）\n"
                            "请具体说明当前环境是否适宜，并提供优化建议。")
                    .arg(cropName)
                    .arg(req.minTemp).arg(req.maxTemp).arg(currentTempTime)
                    .arg(req.minHumidity).arg(req.maxHumidity).arg(currentHumidityTime)
                    .arg(req.minLight).arg(req.maxLight).arg(currentLightTime);

    QString auth;
    auth = "Bearer "+ QString("b259b2ca-fae5-427b-a2ff-813765666a3c");
    qDebug()<<"auth is" << auth;
    //封装火山api请求需要的json格式类型数据
    QJsonObject obj;
    obj.insert("model", "ep-20250707090657-bgn6n");
    QJsonArray message;
    QJsonObject systemobj;
    systemobj.insert("role","system") ;
    systemobj.insert("content","你是农业专家");
    message.append(systemobj) ;
    QJsonObject usrobj;
    usrobj.insert("role","user") ;
    usrobj.insert("content",prompt);
    message.append(usrobj);
    obj.insert("messages", message);
    qDebug()<<"obj is" << obj;
    //实例化网络请求
    QNetworkRequest req_send;
    //表明网络请求发起的请求地址
    QUrl url("https://ark.cn-beijing.volces.com/api/v3/chat/completions");
    req_send.setUrl(url);
    //设置网络请求头
    req_send.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    req_send.setRawHeader("Authorization", auth.toUtf8());
    //发起post网络请求
    manger->post(req_send, QJsonDocument(obj).toJson());

    // 界面反馈
    ui->aiResponseTextEdit->setPlainText("请求发送中...");
    ui->getAdviceButton->setEnabled(false);
}

